'use client'

import { useState, useEffect } from 'react'
import { EyeIcon, DocumentDuplicateIcon } from '@heroicons/react/24/outline'

interface TextExtraction {
  id: number
  videoId: number
  extractedText: string
  confidence: number | null
  language: string | null
  method: string
  status: string
  createdAt: string
  video: {
    title: string | null
    author: string | null
    url: string
  }
}

export default function TextsPage() {
  const [extractions, setExtractions] = useState<TextExtraction[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedText, setSelectedText] = useState<string | null>(null)

  useEffect(() => {
    fetchExtractions()
  }, [])

  const fetchExtractions = async () => {
    try {
      const response = await fetch('/api/tiktok/texts')
      if (response.ok) {
        const data = await response.json()
        setExtractions(data.extractions)
      }
    } catch (error) {
      console.error('Failed to fetch extractions:', error)
    } finally {
      setLoading(false)
    }
  }

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text)
      alert('文案已复制到剪贴板')
    } catch (error) {
      console.error('Failed to copy text:', error)
      alert('复制失败')
    }
  }

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      pending: { color: 'bg-yellow-100 text-yellow-800', text: '处理中' },
      completed: { color: 'bg-green-100 text-green-800', text: '已完成' },
      failed: { color: 'bg-red-100 text-red-800', text: '失败' }
    }
    
    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.pending
    
    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${config.color}`}>
        {config.text}
      </span>
    )
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div>
      <div className="sm:flex sm:items-center">
        <div className="sm:flex-auto">
          <h1 className="text-xl font-semibold text-gray-900">文案管理</h1>
          <p className="mt-2 text-sm text-gray-700">
            查看和管理从TikTok视频中提取的文案内容
          </p>
        </div>
      </div>

      {/* 文案列表 */}
      <div className="mt-8 flex flex-col">
        <div className="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
          <div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
            <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
              <table className="min-w-full divide-y divide-gray-300">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      视频信息
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      提取方法
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      状态
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      置信度
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      提取时间
                    </th>
                    <th className="relative px-6 py-3">
                      <span className="sr-only">操作</span>
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {extractions.map((extraction) => (
                    <tr key={extraction.id}>
                      <td className="px-6 py-4">
                        <div className="flex items-center">
                          <div>
                            <div className="text-sm font-medium text-gray-900">
                              {extraction.video.title || '未知标题'}
                            </div>
                            <div className="text-sm text-gray-500">
                              作者: {extraction.video.author || '未知'}
                            </div>
                            <div className="text-sm text-gray-400 max-w-md truncate mt-1">
                              {extraction.extractedText}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                          {extraction.method}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {getStatusBadge(extraction.status)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {extraction.confidence ? `${Math.round(extraction.confidence * 100)}%` : '-'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {new Date(extraction.createdAt).toLocaleDateString()}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <div className="flex space-x-2">
                          <button
                            onClick={() => setSelectedText(extraction.extractedText)}
                            className="text-indigo-600 hover:text-indigo-900"
                            title="查看完整文案"
                          >
                            <EyeIcon className="h-5 w-5" />
                          </button>
                          <button
                            onClick={() => copyToClipboard(extraction.extractedText)}
                            className="text-green-600 hover:text-green-900"
                            title="复制文案"
                          >
                            <DocumentDuplicateIcon className="h-5 w-5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {extractions.length === 0 && (
                <div className="text-center py-12">
                  <p className="text-gray-500">暂无文案数据，请先采集视频并提取文案</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 文案详情模态框 */}
      {selectedText && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
          <div className="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
            <div className="mt-3">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-medium text-gray-900">完整文案内容</h3>
                <button
                  onClick={() => setSelectedText(null)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <span className="sr-only">关闭</span>
                  ✕
                </button>
              </div>
              <div className="mt-2 p-4 bg-gray-50 rounded-md">
                <p className="text-sm text-gray-700 whitespace-pre-wrap">
                  {selectedText}
                </p>
              </div>
              <div className="mt-4 flex justify-end space-x-3">
                <button
                  onClick={() => copyToClipboard(selectedText)}
                  className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  复制文案
                </button>
                <button
                  onClick={() => setSelectedText(null)}
                  className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
